// 登录界面组件 - 基于用户需求说明1.2

import React, { useState, useEffect } from 'react';
import { User, Shield, Fingerprint, Key, Eye, EyeOff, Clock } from 'lucide-react';

interface LoginScreenProps {
  onLogin: (userType: 'passenger' | 'safety_officer') => void;
}

const LoginScreen: React.FC<LoginScreenProps> = ({ onLogin }) => {
  const [selectedUserType, setSelectedUserType] = useState<'passenger' | 'safety_officer' | null>(null);
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [autoLoginCountdown, setAutoLoginCountdown] = useState(5);
  const [isAutoLogin, setIsAutoLogin] = useState(false);

  // 模拟上次登录用户（实际应用中从本地存储获取）
  const [lastUserType] = useState<'passenger' | 'safety_officer' | null>('safety_officer');

  useEffect(() => {
    // 如果有上次登录用户，启动5秒自动登录倒计时
    if (lastUserType) {
      setIsAutoLogin(true);
      const timer = setInterval(() => {
        setAutoLoginCountdown(prev => {
          if (prev <= 1) {
            clearInterval(timer);
            handleAutoLogin();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [lastUserType]);

  const handleAutoLogin = () => {
    if (lastUserType) {
      setIsLoading(true);
      setTimeout(() => {
        onLogin(lastUserType);
      }, 500);
    }
  };

  const handleManualLogin = () => {
    if (!selectedUserType || !password) return;

    setIsLoading(true);
    
    // 模拟登录验证
    setTimeout(() => {
      // 简单的密码验证（实际应用中需要更安全的验证）
      const validPasswords = {
        passenger: '123456',
        safety_officer: 'admin123'
      };

      if (password === validPasswords[selectedUserType]) {
        onLogin(selectedUserType);
      } else {
        alert('密码错误，请重试');
        setIsLoading(false);
      }
    }, 1000);
  };

  const handleUserTypeSelect = (userType: 'passenger' | 'safety_officer') => {
    setSelectedUserType(userType);
    setPassword('');
    setIsAutoLogin(false);
    setAutoLoginCountdown(0);
  };

  const handleFingerprintLogin = () => {
    if (!selectedUserType) return;
    
    setIsLoading(true);
    // 模拟指纹识别
    setTimeout(() => {
      onLogin(selectedUserType);
    }, 1500);
  };

  return (
    <div className="fixed inset-0 bg-gradient-to-br from-gray-900 via-blue-900 to-gray-900 flex items-center justify-center z-50">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute top-1/4 left-1/4 w-64 h-64 bg-primary-500/10 rounded-full blur-3xl animate-pulse" />
        <div className="absolute bottom-1/4 right-1/4 w-64 h-64 bg-blue-500/10 rounded-full blur-3xl animate-pulse" />
      </div>

      <div className="relative z-10 w-full max-w-md mx-auto px-6">
        {/* 标题 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">
            软通动力自动驾驶小巴
          </h1>
          <p className="text-gray-300">HMI 系统登录</p>
        </div>

        {/* 自动登录提示 */}
        {isAutoLogin && lastUserType && (
          <div className="mb-6 p-4 bg-primary-600/20 border border-primary-500/30 rounded-lg">
            <div className="flex items-center gap-3">
              <Clock size={20} className="text-primary-400" />
              <div className="flex-1">
                <p className="text-sm text-primary-400">
                  检测到上次登录用户，{autoLoginCountdown}秒后自动登录
                </p>
                <p className="text-xs text-gray-400 mt-1">
                  {lastUserType === 'passenger' ? '乘客模式' : '安全员模式'}
                </p>
              </div>
            </div>
            <button
              onClick={() => setIsAutoLogin(false)}
              className="mt-2 text-xs text-gray-400 hover:text-white transition-colors"
            >
              取消自动登录
            </button>
          </div>
        )}

        {/* 用户类型选择 */}
        {!isAutoLogin && (
          <div className="mb-6">
            <h3 className="text-lg font-medium text-white mb-4 text-center">选择用户类型</h3>
            <div className="grid grid-cols-2 gap-4">
              <button
                onClick={() => handleUserTypeSelect('passenger')}
                className={`p-4 rounded-lg border-2 transition-all ${
                  selectedUserType === 'passenger'
                    ? 'border-primary-500 bg-primary-600/20 text-primary-400'
                    : 'border-gray-600 bg-gray-800/50 text-gray-300 hover:border-gray-500'
                }`}
              >
                <User size={32} className="mx-auto mb-2" />
                <h4 className="font-medium">乘客</h4>
                <p className="text-xs text-gray-400 mt-1">查看车辆状态</p>
              </button>
              
              <button
                onClick={() => handleUserTypeSelect('safety_officer')}
                className={`p-4 rounded-lg border-2 transition-all ${
                  selectedUserType === 'safety_officer'
                    ? 'border-primary-500 bg-primary-600/20 text-primary-400'
                    : 'border-gray-600 bg-gray-800/50 text-gray-300 hover:border-gray-500'
                }`}
              >
                <Shield size={32} className="mx-auto mb-2" />
                <h4 className="font-medium">安全员</h4>
                <p className="text-xs text-gray-400 mt-1">完整控制权限</p>
              </button>
            </div>
          </div>
        )}

        {/* 登录表单 */}
        {selectedUserType && !isAutoLogin && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                密码验证
              </label>
              <div className="relative">
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码"
                  className="w-full px-4 py-3 pl-12 pr-12 bg-gray-800/50 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
                />
                <Key size={20} className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white"
                >
                  {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
            </div>

            {/* 登录按钮 */}
            <div className="space-y-3">
              <button
                onClick={handleManualLogin}
                disabled={!password || isLoading}
                className="w-full py-3 bg-primary-600 hover:bg-primary-500 disabled:bg-gray-600 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                {isLoading ? (
                  <>
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    登录中...
                  </>
                ) : (
                  <>
                    <Key size={20} />
                    密码登录
                  </>
                )}
              </button>

              <button
                onClick={handleFingerprintLogin}
                disabled={isLoading}
                className="w-full py-3 bg-gray-700 hover:bg-gray-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
              >
                <Fingerprint size={20} />
                指纹登录
              </button>
            </div>
          </div>
        )}

        {/* 权限说明 */}
        <div className="mt-8 p-4 bg-gray-800/30 rounded-lg">
          <h4 className="text-sm font-medium text-gray-300 mb-2">权限说明</h4>
          <div className="space-y-2 text-xs text-gray-400">
            <div className="flex items-start gap-2">
              <User size={14} className="mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium">乘客权限：</p>
                <p>查看车辆状态、导航信息、紧急呼叫和停车</p>
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Shield size={14} className="mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium">安全员权限：</p>
                <p>完整系统控制、模块监控、数据录制、配置管理</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginScreen;
